package com.alks.function.handler.excel;

import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alks.common.utils.beanutils.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: chen
 * @date: 2024/11/28
 * @description: 步峰针车日报表自定义样式处理
 */
public class ReportMonthCXHandler implements CellWriteHandler {

    private Map<Integer, Map<Integer, Integer>> cache = new HashMap<>();

    private final Integer width = 255;

    private List<Integer> mergeRow;
    private List<Integer> sheetOneMergeRow;
    private List<Integer> sheetTwoMergeRow;

    public ReportMonthCXHandler(List<Integer> sheetOneMergeRow, List<Integer> sheetTwoMergeRow) {
        this.sheetOneMergeRow = sheetOneMergeRow;
        this.sheetTwoMergeRow = sheetTwoMergeRow;
    }

    @Override
    public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {
        if (writeSheetHolder.getSheetNo() == 0) {
            mergeRow = sheetOneMergeRow;
        } else {
            mergeRow = sheetTwoMergeRow;
        }
    }

    @Override
    public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        Sheet sheet = writeSheetHolder.getSheet();
        // 冻结窗口
        sheet.createFreezePane(1, 1);
    }

    @Override
    public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, WriteCellData<?> cellData, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        CellWriteHandler.super.afterCellDataConverted(writeSheetHolder, writeTableHolder, cellData, cell, head, relativeRowIndex, isHead);
    }

    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<WriteCellData<?>> list, Cell cell, Head head, Integer integer, Boolean isHead) {
        // 当前行
        int curRowIndex = cell.getRowIndex();
        // 当前列
        int curColIndex = cell.getColumnIndex();
        Workbook workbook = cell.getSheet().getWorkbook();

        if (curRowIndex > 0 && !mergeRow.contains(curRowIndex)) {
            // 调整列宽
            int num = 100000;
            Map<Integer, Integer> maxColumnWidthMap = cache.computeIfAbsent(writeSheetHolder.getSheetNo(), k -> new HashMap<>((int) (num / 0.75 + 1.0)));

            Integer columnWidth = this.dataLength(list);
            if (columnWidth < 5) {
                columnWidth = 5;
            }
            if (columnWidth > width) {
                columnWidth = width;
            }

            Integer maxColumnWidth = maxColumnWidthMap.get(cell.getColumnIndex());
            if (maxColumnWidth == null || columnWidth > maxColumnWidth) {
                maxColumnWidthMap.put(cell.getColumnIndex(), columnWidth);
                writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
            }

        }

        // 根据是否为表头设置样式
        if (curRowIndex < 1 || mergeRow.contains(curRowIndex)) {
            if (curRowIndex < 1) {
                XSSFCellStyle headerStyle = createHeaderStyle(workbook);
                cell.setCellStyle(headerStyle);
                cell.getRow().setHeight((short) (25 * 20)); // 设置行高
            } else {
                XSSFCellStyle headerStyle = createDataStyle(workbook);
                cell.setCellStyle(headerStyle);
            }
            if (curColIndex > 0) {
                mergeWithPrevRowLeft(writeSheetHolder, cell, curRowIndex, curColIndex);
            }
            // 垂直方向合并
            if (curRowIndex > 0) {
                mergeWithPrevRow(writeSheetHolder, cell, curRowIndex, curColIndex);
            }
        } else {
            XSSFCellStyle dataStyle = createDataStyle(workbook);
            cell.setCellStyle(dataStyle);
        }
    }

    /**
     * 合并上一行的单元格
     * @param writeSheetHolder
     * @param cell
     * @param curRowIndex
     * @param curColIndex
     */
    private void mergeWithPrevRow(WriteSheetHolder writeSheetHolder, Cell cell, int curRowIndex, int curColIndex) {
        // 获取当前行的当前列和上一行的当前列列数据，通过上一行数据是否相同进行合并
        Object curData = cell.getCellTypeEnum() == CellType.STRING ? cell.getStringCellValue() : cell.getNumericCellValue();
        if (isBlank(cell)) return;
        Cell preCell = cell.getSheet().getRow(curRowIndex - 1).getCell(curColIndex);
        Object preData = null;
        try {
            preData = preCell.getCellTypeEnum() == CellType.STRING ? preCell.getStringCellValue() : preCell.getNumericCellValue();
        } catch (NullPointerException ex) {
            return;
        }

        // 比较当前行的第一列的单元格与上一行是否相同，相同合并当前单元格与上一行
        if (curData.equals(preData)) {
            Sheet sheet = writeSheetHolder.getSheet();
            List<CellRangeAddress> mergedRegions = sheet.getMergedRegions();
            boolean isMerged = false;
            for (int i = 0; i < mergedRegions.size() && !isMerged; i++) {
                CellRangeAddress cellRangeAddr = mergedRegions.get(i);
                // 若上一个单元格已经被合并，则先移出原有的合并单元，再重新添加合并单元
                if (cellRangeAddr.isInRange(curRowIndex - 1, curColIndex)) {
                    sheet.removeMergedRegion(i);
                    cellRangeAddr.setLastRow(curRowIndex);
                    sheet.addMergedRegion(cellRangeAddr);
                    isMerged = true;
                }
            }
            // 若上一个单元格未被合并，则新增合并单元
            if (!isMerged) {
                CellRangeAddress cellRangeAddress = new CellRangeAddress(curRowIndex - 1, curRowIndex, curColIndex, curColIndex);
                sheet.addMergedRegion(cellRangeAddress);
            }
        }
    }

    /**
     * 合并左边单元格
     * @param writeSheetHolder
     * @param cell
     * @param curRowIndex
     * @param curColIndex
     */
    private void mergeWithPrevRowLeft(WriteSheetHolder writeSheetHolder, Cell cell, int curRowIndex, int curColIndex) {
        // 获取当前行的当前列和上一列数据，通过上一列数据是否相同进行合并
        Object curData = cell.getCellTypeEnum() == CellType.STRING ? cell.getStringCellValue() : cell.getNumericCellValue();
        if (isBlank(cell)) return;
        Cell preCell = cell.getSheet().getRow(curRowIndex).getCell(curColIndex - 1);
        Object preData = preCell.getCellTypeEnum() == CellType.STRING ? preCell.getStringCellValue() : preCell.getNumericCellValue();

        if (curData.equals(preData)) {
            Sheet sheet = writeSheetHolder.getSheet();
            List<CellRangeAddress> mergedRegions = sheet.getMergedRegions();
            boolean isMerged = false;
            for (int i = 0; i < mergedRegions.size() && !isMerged; i++) {
                CellRangeAddress cellRangeAddr = mergedRegions.get(i);
                // 若上一个单元格已经被合并，则先移出原有的合并单元，再重新添加合并单元
                if (cellRangeAddr.isInRange(curRowIndex, curColIndex - 1)) {
                    sheet.removeMergedRegion(i);
                    cellRangeAddr.setLastColumn(curColIndex);
                    sheet.addMergedRegion(cellRangeAddr);
                    isMerged = true;
                }
            }
            // 若上一个单元格未被合并，则新增合并单元
            if (!isMerged) {
                CellRangeAddress cellRangeAddress = new CellRangeAddress(curRowIndex, curRowIndex, curColIndex - 1, curColIndex);
                sheet.addMergedRegion(cellRangeAddress);
            }
        }
    }

    /**
     * 单元格是否为空  包含空字符串
     * @param cell
     * @return
     */
    private boolean isBlank(Cell cell) {
        CellType type = cell.getCellType();
        if (CellType.STRING == type) {
            return StringUtils.isEmpty(cell.getStringCellValue());
        } else if (CellType.BLANK == type){
            return true;
        }
        return false;
    }

    /**
     * 计算数据长度
     * @param cellDataList
     * @return
     */
    private Integer dataLength(List<WriteCellData<?>> cellDataList) {
        WriteCellData<?> cellData = cellDataList.get(0);
        CellDataTypeEnum type = cellData.getType();
        if (type == null) {
            return -1;
        } else {
            switch (type) {
                case STRING:
                    return cellData.getStringValue().getBytes().length + 1;
                case BOOLEAN:
                    return cellData.getBooleanValue().toString().getBytes().length + 1;
                case NUMBER:
                    return cellData.getNumberValue().stripTrailingZeros().toString().getBytes().length + 1;
                default:
                    return -1;
            }
        }
    }

    /**
     * 设置表头样式
     * @param workbook
     * @return
     */
    private XSSFCellStyle createHeaderStyle(Workbook workbook) {
        XSSFCellStyle cellStyle = (XSSFCellStyle) workbook.createCellStyle();
        byte[] rgb = new byte[]{(byte) 241, (byte) 242, (byte) 246}; // 表头背景色
        XSSFColor color = new XSSFColor(rgb, new StylesTable().getIndexedColors());
        cellStyle.setFillForegroundColor(color);
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        Font font = workbook.createFont();
        font.setBold(true);
        font.setFontHeightInPoints((short) 12);
        cellStyle.setFont(font);

        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        setAllBorders(cellStyle);
        return cellStyle;
    }

    /**
     * 设置数据样式
     * @param workbook
     * @return
     */
    private XSSFCellStyle createDataStyle(Workbook workbook) {
        XSSFCellStyle cellStyle = (XSSFCellStyle) workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        setAllBorders(cellStyle);

        return cellStyle;
    }

    private static void setAllBorders(XSSFCellStyle cellStyle) {
        cellStyle.setBorderTop(BorderStyle.THIN);
        cellStyle.setBorderBottom(BorderStyle.THIN);
        cellStyle.setBorderLeft(BorderStyle.THIN);
        cellStyle.setBorderRight(BorderStyle.THIN);
    }


}
